package com.css.zfzx.sjcj.modules.hddcImportantSurfaceFeature.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.excel.handler.ActiveFaultVerifyBaseHandler;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcImportantSurfaceFeature.repository.HddcImportantsurfacefeatureNativeRepository;
import com.css.zfzx.sjcj.modules.hddcImportantSurfaceFeature.repository.HddcImportantsurfacefeatureRepository;
import com.css.zfzx.sjcj.modules.hddcImportantSurfaceFeature.repository.entity.HddcImportantsurfacefeatureEntity;
import com.css.zfzx.sjcj.modules.hddcImportantSurfaceFeature.service.HddcImportantsurfacefeatureService;
import com.css.zfzx.sjcj.modules.hddcImportantSurfaceFeature.viewobjects.HddcImportantsurfacefeaturePageVO;
import com.css.zfzx.sjcj.modules.hddcImportantSurfaceFeature.viewobjects.HddcImportantsurfacefeatureQueryParams;
import com.css.zfzx.sjcj.modules.hddcImportantSurfaceFeature.viewobjects.HddcImportantsurfacefeatureVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 地质调查数据-重要地名地物-点管理
 *
 * @author lihelei
 * @date 2020-11-30
 */
@Service
public class HddcImportantsurfacefeatureServiceImpl implements HddcImportantsurfacefeatureService {

    private final HddcImportantsurfacefeatureRepository hddcImportantsurfacefeatureRepository;
    private final HddcImportantsurfacefeatureNativeRepository hddcImportantsurfacefeatureNativeRepository;
    private final ActiveFaultVerifyBaseHandler activeFaultVerifyBaseHandler;

    @Autowired
    public HddcImportantsurfacefeatureServiceImpl(HddcImportantsurfacefeatureRepository hddcImportantsurfacefeatureRepository,
                                                  HddcImportantsurfacefeatureNativeRepository hddcImportantsurfacefeatureNativeRepository,
                                                  ActiveFaultVerifyBaseHandler activeFaultVerifyBaseHandler) {
        this.hddcImportantsurfacefeatureRepository = hddcImportantsurfacefeatureRepository;
        this.hddcImportantsurfacefeatureNativeRepository = hddcImportantsurfacefeatureNativeRepository;
        this.activeFaultVerifyBaseHandler = activeFaultVerifyBaseHandler;
    }

    @Override
    public JSONObject queryHddcImportantsurfacefeatures(HddcImportantsurfacefeatureQueryParams queryParams, int curPage, int pageSize, String sort, String order) {
        Page<HddcImportantsurfacefeaturePageVO> hddcImportantsurfacefeaturePage = this.hddcImportantsurfacefeatureNativeRepository.queryHddcImportantsurfacefeatures(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcImportantsurfacefeaturePage);
    }

    @Override
    public HddcImportantsurfacefeatureEntity getHddcImportantsurfacefeature(String id) {
        return this.hddcImportantsurfacefeatureRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcImportantsurfacefeatureEntity saveHddcImportantsurfacefeature(HddcImportantsurfacefeatureEntity hddcImportantsurfacefeature) {
        String uuid = UUIDGenerator.getUUID();
        hddcImportantsurfacefeature.setUuid(uuid);
        hddcImportantsurfacefeature.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcImportantsurfacefeature.setCreateTime(now);
        hddcImportantsurfacefeature.setUpdateTime(now);
        hddcImportantsurfacefeature.setIsValid(PlatformConstants.Y);
        hddcImportantsurfacefeature.setQualityinspectionStatus(PlatformConstants.N);
        hddcImportantsurfacefeature.setExtends10(PlatformConstants.Y);
        this.hddcImportantsurfacefeatureRepository.save(hddcImportantsurfacefeature);
        return hddcImportantsurfacefeature;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcImportantsurfacefeatureEntity updateHddcImportantsurfacefeature(HddcImportantsurfacefeatureEntity hddcImportantsurfacefeature) {
        HddcImportantsurfacefeatureEntity entity = hddcImportantsurfacefeatureRepository.findById(hddcImportantsurfacefeature.getUuid()).get();
        UpdateUtil.copyNullProperties(entity, hddcImportantsurfacefeature);
        hddcImportantsurfacefeature.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcImportantsurfacefeature.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcImportantsurfacefeatureRepository.save(hddcImportantsurfacefeature);
        return hddcImportantsurfacefeature;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcImportantsurfacefeatures(List<String> ids) {
        List<HddcImportantsurfacefeatureEntity> hddcImportantsurfacefeatureList = this.hddcImportantsurfacefeatureRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(hddcImportantsurfacefeatureList) && hddcImportantsurfacefeatureList.size() > 0) {
            for (HddcImportantsurfacefeatureEntity hddcImportantsurfacefeature : hddcImportantsurfacefeatureList) {
                hddcImportantsurfacefeature.setIsValid(PlatformConstants.N);
                hddcImportantsurfacefeature.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcImportantsurfacefeature.setUpdateTime(new Date());
                this.hddcImportantsurfacefeatureRepository.save(hddcImportantsurfacefeature);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcImportantsurfacefeatureQueryParams queryParams, HttpServletResponse response) {
        List<HddcImportantsurfacefeatureEntity> yhDisasterEntities = hddcImportantsurfacefeatureNativeRepository.exportYhDisasters(queryParams);
        List<HddcImportantsurfacefeatureVO> list = new ArrayList<>();
        for (HddcImportantsurfacefeatureEntity entity : yhDisasterEntities) {
            HddcImportantsurfacefeatureVO yhDisasterVO = new HddcImportantsurfacefeatureVO();
            BeanUtils.copyProperties(entity, yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "重要地名地物-点", "重要地名地物-点",
                HddcImportantsurfacefeatureVO.class, "重要地名地物-点.xls", response);
    }

    @Override
    public String importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(activeFaultVerifyBaseHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcImportantsurfacefeatureVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcImportantsurfacefeatureVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcImportantsurfacefeatureVO yhDisasterVO : result.getFailList()) {
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcImportantsurfacefeatureVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     */
    public void saveDisasterList(List<HddcImportantsurfacefeatureVO> list) {
        for (HddcImportantsurfacefeatureVO hddcImportantsurfacefeatureVO : list) {
            HddcImportantsurfacefeatureEntity yhDisasterEntity = new HddcImportantsurfacefeatureEntity();
            BeanUtils.copyProperties(hddcImportantsurfacefeatureVO, yhDisasterEntity);
            saveHddcImportantsurfacefeature(yhDisasterEntity);
        }
    }

    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcImportantsurfacefeatureEntity> hddcImportantsurfacefeatureList = this.hddcImportantsurfacefeatureRepository.queryHddcImportantsurfacefeaturesByProjectId(projectIds);
        if (!PlatformObjectUtils.isEmpty(hddcImportantsurfacefeatureList) && hddcImportantsurfacefeatureList.size() > 0) {
            for (HddcImportantsurfacefeatureEntity hddcImportantsurfacefeature : hddcImportantsurfacefeatureList) {
                hddcImportantsurfacefeature.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcImportantsurfacefeature.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcImportantsurfacefeature.setIsValid(PlatformConstants.N);
                this.hddcImportantsurfacefeatureRepository.save(hddcImportantsurfacefeature);
            }
        }
    }

    @Override
    public void deleteByTaskId(List<String> taskIds) {
        List<HddcImportantsurfacefeatureEntity> hddcImportantsurfacefeatureList = this.hddcImportantsurfacefeatureRepository.queryHddcImportantsurfacefeaturesByTaskId(taskIds);
        if (!PlatformObjectUtils.isEmpty(hddcImportantsurfacefeatureList) && hddcImportantsurfacefeatureList.size() > 0) {
            for (HddcImportantsurfacefeatureEntity hddcImportantsurfacefeature : hddcImportantsurfacefeatureList) {
                hddcImportantsurfacefeature.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcImportantsurfacefeature.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcImportantsurfacefeature.setIsValid(PlatformConstants.N);
                this.hddcImportantsurfacefeatureRepository.save(hddcImportantsurfacefeature);
            }
        }
    }

}
